package com.dhecp.project.storage.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.DateUtil;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.storage.domain.OtherCost;
import com.dhecp.project.storage.domain.StockControl;
import com.dhecp.project.storage.domain.StockControlRunning;
import com.dhecp.project.storage.service.OtherCostService;
import com.dhecp.project.storage.service.StockControlRunningService;
import com.dhecp.project.storage.service.StockControlService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @program: kjecp
 * @description: 仓储 库存管理
 * @author: hlf
 * @create: 2022-09-01 16:43
 */
@Controller
@RequestMapping("/storage/stockcontrol")
public class StockControlController extends BaseModuleController {

    private String prefix = "storage/stockcontrol";
    private String moduleTable = ModuleTable.STOCK_CONTROL;
    
    @Autowired
    private StockControlService storageService;
    
    @Autowired
    private StockControlRunningService stockControlRunningService;

    @Autowired
    private OtherCostService otherCostService;
    
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    /**
     *@Description: 打开查询列表页
     *@Param: [params]
     *@return: org.springframework.web.servlet.ModelAndView
     *@Author: hlf
     *@date: 2022-05-09 11:39
     */
    @RequiresPermissions("storage:stockcontrol:view")
    @GetMapping()
    public ModelAndView listPage(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new StockControl()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/stockcontrol"); //页面路径
        params.put("toolBarWidth", 0);
        params.put("checkBox", "yes");

        ModelAndView mv = this.openListPage(params);
        mv.addObject("storage", "stockcontrol");

        OtherCost cost = new OtherCost();
        cost = otherCostService.getTop1(params);
        mv.addObject("cost", cost);
        mv.setViewName(prefix + "/stockcontrol");
        return mv;
    }

    /**
     * @Description: 打开制单页
     * @Param: [params] nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: hlf
     * @date: 2022-05-09 11:39
     */
    @RequiresPermissions("storage:stockcontrol:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new StockControl()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
        List<Object> fieldsList = new ArrayList<Object>(); 			//生成控件的字段和属性
        List<Object> fieldsHiddenList = new ArrayList<Object>(); 	//隐藏的字段和属性
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        StockControl stockControl = new StockControl();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            stockControl = storageService.findByGuid(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
            params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
            dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
            if (dicFieldsList.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                for (SysDictionaryForPageField dicFields : dicFieldsList){
                    Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);

                    if (stockControl!=null){
                        Map<String, Object> infoData = TypeUtils.entityToMap(stockControl);
                        fieldsListMap.put("fieldContent", infoData.get(fieldsListMap.get("fields")));
                    }else{
                        fieldsListMap.put("fieldContent", "");

                    }
                    if (fieldsListMap.get("fieldFrontType") == null){
                        fieldsListMap.put("fieldFrontType", "t_text");
                    }

                    if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){	//显示的字段
                        fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                    }else {	//隐藏的字段
                        fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                    }
                }
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap)); //各字段及属性
        mv.addObject("fieldsList", fieldsList);				//显示的字段
        mv.addObject("fieldsHiddenList", fieldsHiddenList);	//隐藏的字段
        mv.addObject("stockControl", stockControl);	//字段
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/stockcontrol_edit");
        return mv;
    }

    /**
     *@Description: 查询页 列表数据
     *@Param: [params]
     *@return: com.dhecp.common.core.page.TableDataInfo
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions("storage:stockcontrol:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        List<StockControl> list = new ArrayList<StockControl>();
        try {
            list = storageService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 保存数据
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 11:41
     */
    @RequiresPermissions(value = {"storage:stockcontrol:add", "storage:stockcontrol:edit", "storage:stockcontrol:delete"}, logical = Logical.OR)
    @Log(title = "库存调拨价格修改", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editSave(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = storageService.saveData(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 打开选择页面
     *@Param: [params]
     *@return: org.springframework.web.servlet.ModelAndView
     *@Author: hlf
     *@date: 2022-09-05 14:10
     */
    @GetMapping("/select")
    public ModelAndView selectModule(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new StockControl()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("toolBarWidth", 0);
        if(params.get("pagetype") !=null && params.get("pagetype").toString().equalsIgnoreCase("checkbox"))params.put("checkBox", "yes");
        else params.put("radio", "yes");
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();

        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("prefix", prefix);
        mv.addObject("moduleTable", moduleTable);
        mv.setViewName("common/select");
        return mv;
    }

    /**
     *@Description: 数据导出Excel
     *@Param: [params]
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:41
     */
    @RequiresPermissions("storage:stockcontrol:export")
    @Log(title = "库存管理导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new StockControl());

        List<StockControl> list = storageService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<StockControl> util = new ExportExcelUtils<StockControl>(moduleTable,new StockControl());
        return util.exportExcel(list, fieldList, "库存管理", "export");
    }

    /**
     *@Description: 详情信息
     *@Author: xdh
     *@date: 2023-03-12 20:15
     */
    @GetMapping("/toDetail")
    public ModelAndView toDetail(String guid){
    	
    	List<StockControlRunning> listEntity = stockControlRunningService.queryListByGuidStockControl(guid);
        
        // 详情数组
        List<ToDetailDto.RowDto> rows = new ArrayList<ToDetailDto.RowDto>();
        for(StockControlRunning entity : listEntity) {
        	String productCode = entity.getProductCode();
        	String productName = "";
        	String vGsBm = entity.getvGsBm();
        	String vGsMc = "";
        	String vGsJc = "";
        	String locationHw = entity.getLocationHw();
        	Integer productNumChange = entity.getProductNumChange();
        	Integer productNumLeft = entity.getProductNumLeft();
        	String createTime = DateUtil.getYYYY_MM_DD_HH_mm_ss(entity.getCreateTime());
        	ToDetailDto.RowDto row = new ToDetailDto.RowDto(productCode, productName, vGsBm, vGsMc, vGsJc, locationHw, productNumChange, productNumLeft, createTime);
        	rows.add(row);
        }
        
		ToDetailDto dto = new ToDetailDto(guid, rows);
		
        ModelAndView mv = new ModelAndView();
        mv.setViewName(prefix + "/toDetail");
        mv.addObject("dto", dto);
        return mv;
    }
	@Data
	@AllArgsConstructor
	private static class ToDetailDto{
		private String guid; // 库存guid
		private List<RowDto> rows; // 详情信息数组@Data

		@Data
		@AllArgsConstructor
		public static class RowDto {
			private String productCode; // 
			private String productName; // 
			private String vGsBm; // 
			private String vGsMc; // 
			private String vGsJc; // 
			private String locationHw; // 
			private Integer productNumChange; // 库存变动数量
			private Integer productNumLeft; // 人数，如：141
			private String createTime; // 操作时间
		}
	}
    
}
